# coding:utf-8

import os

import pymysql
import requests
from flask import Flask
from flask import request, session, redirect
from werkzeug.utils import import_string
from config import Config


conf = Config()

requests.packages.urllib3.disable_warnings()
pymysql.install_as_MySQLdb()

# 所有的蓝图
blueprints = [
    'blues.alerts:bp',
    'blues.cloud:bp',
    'blues.cluster:bp',
    'blues.cmdb:bp',
    'blues.job:bp',
    'blues.login:bp',
    'blues.mon:bp',
    'blues.nav:bp',
]


def create_app():
    app = Flask(__name__, template_folder='./templates', static_url_path='/static', static_folder='./static')
    app.config["JSON_AS_ASCII"] = False  # 使通过jsonify返回的中文显示正常，否则显示为ASCII码
    app.config['SECRET_KEY'] = os.urandom(24)  # 生成随机数种子，用于产生SessionID
    # Admin配置
    app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
    # APS配置
    app.config['SCHEDULER_API_ENABLED'] = True
    app.config['SCHEDULER_API_ENABLED'] = "Asia/Shanghai"
    # job持久化
    # from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
    # app.config['SCHEDULER_JOBSTORES'] = {'default': SQLAlchemyJobStore(url=conf.MYSQL_URI)}


    # flask-admin后台
    from admin import admin
    admin.init_app(app)

    # 将蓝图注册到app中
    for bp_name in blueprints:
        bp = import_string(bp_name)
        app.register_blueprint(bp)

    # 初始化db
    # from . import db
    # db.init_db(app)

    # 针对app实例定义全局拦截器
    @app.before_request
    def before():
        if os.getenv("FLASK_DEBUG") == "1":
            return
        url = request.path

        # 需要通过的网站接口列表
        pass_list = ['/login', '/api/v1/login', '/favicon.ico', '/logout', '/api/v1/cloud/generate_ecs_stats']
        if url in pass_list:
            return
        # suffix = url.endswith('.png') or url.endswith('.jpg') or url.endswith('.css') or url.endswith('.js')
        special_prefix = url.startswith('/static/') or url.startswith('/scheduler')
        if special_prefix:
            return
        if session.get('islogin') != 'true':
            # 获取之前的url，登录之后跳转回去
            print("login back_path:" + request.path)
            return redirect('/login?backpath=' + request.path)
        return

    return app


if __name__ == '__main__':
    # 启动计划任务
    from scheduler import cron_job

    app = create_app()
    # app.config.from_object(APSConfig())
    cron_job.scheduler.init_app(app)
    cron_job.scheduler.start()

    # 启动Flask App
    # app.debug = True
    app.run(host='0.0.0.0')
